package gl.java.util;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
public class UserConnectionPool {
    private Map<Channel, Integer> mChannelMap;
    private Map<Integer, Channel> mUserIDMap;

    public UserConnectionPool() {
        mChannelMap = new ConcurrentHashMap<Channel, Integer>();
        mUserIDMap = new ConcurrentHashMap<Integer, Channel>();
    }

    private static class SinglonHolder {
        final static UserConnectionPool holder = new UserConnectionPool();
    }

    public static UserConnectionPool getInstance() {
        return SinglonHolder.holder;
    }

    public void remove(Channel ctx) {
        if (ctx == null) {
            return;
        }
        Integer id = Integer.MIN_VALUE;
        if (mChannelMap.containsKey(ctx)) {
            id = mChannelMap.get(ctx);
            Integer key = mChannelMap.remove(ctx);
//			logger.info("remove the UserID from ChannelMap: " + key);
            if (mUserIDMap.containsKey(id)) {
                Channel key2 = mUserIDMap.remove(id);
//				logger.info("remove the Channel from UserIDMap: " + key2);
            } else {
//				logger.warn("UserIDMap not exist channel:" + ctx);
            }
        } else {
//			logger.warn("ChannelMap not exist:" + ctx);
        }

    }

    public Channel getChannelHandler(int userID) {

        Channel userInfo = mUserIDMap.get(userID);
        return userInfo == null ? null : userInfo;
    }

    public int getToID(int userID) {
//		Channel userInfo = mUserIDMap.get(userID);
        return 0;
    }

    public int getToID(ChannelHandlerContext ctx) {
        return getToID(getID(ctx.channel()));
    }

    public void put(int userID, Channel ctx) {
        mChannelMap.put(ctx, userID);
        mUserIDMap.put(userID, ctx);
    }

    public boolean containsKey(int id) {
        return mUserIDMap.containsKey(id);
    }

    public Channel getUserInfo(Channel ctx) {
        final Integer userID = mChannelMap.get(ctx);
        return userID == null ? null : mUserIDMap.get(userID);
    }


    public Integer getID(Channel ctx) {
        final Integer integer = mChannelMap.get(ctx);
        return integer == null ? 0 : integer;
    }

    public Set<Channel> getAllChannel() {
        return mChannelMap.keySet();
    }

    public Channel getUserInfo(int id) {
        return mUserIDMap.get(id);
    }

    public List<Channel> toUserList() {
        final ArrayList<Channel> arrayList = new ArrayList<Channel>();
        Set<Integer> keyset = mUserIDMap.keySet();
        for (Integer integer : keyset) {
            arrayList.add(mUserIDMap.get(integer));
        }
        return arrayList;
    }
}
